package zh.dummy.netty.client.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import zh.dummy.netty.NettyClient;
import zh.dummy.netty.client.exception.RepeatedLoginException;
import zh.dummy.netty.client.util.NettyMessageBuilder;
import zh.dummy.netty.client.util.NettyUtil;
import zh.dummy.netty.core.protocol.ErrorType;
import zh.dummy.netty.core.protocol.MessageType;
import zh.dummy.netty.core.protocol.NettyMessage;

public class LoginAuthReqHandler extends ChannelHandlerAdapter{
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	public void channelActive(ChannelHandlerContext ctx){
		if(logger.isDebugEnabled()){
			logger.debug("channelActive start to login");
		}
		ctx.writeAndFlush(NettyMessageBuilder.buildAuthReq());
	}
	
	public void channelRead(ChannelHandlerContext ctx ,Object msg){
		NettyMessage message = (NettyMessage) msg;
		//如果是握手应答消息，需要判断是否认证成功
		if(message.getHeader() != null 
				&& message.getHeader().getType() == MessageType.LOGIN_RESP.value()){
			JSONObject loginResult = (JSONObject) message.getBody();
			if(logger.isInfoEnabled()){
				logger.info("received login response　: "+loginResult.toJSONString());
			}
			byte errorCode = loginResult.getByte("errorCode");
			if(errorCode != ErrorType.SUCCESS.getValue()){
				logger.error("login fail errorCode:{} errorMsg:{}",new Object[]{errorCode,ErrorType.getName(errorCode)});
				ctx.close();
				loginFailProcess();
				ctx.fireExceptionCaught(new RepeatedLoginException("重复登录"));
			}else{
				NettyUtil.setClientId(loginResult.getString("id"));
				ctx.fireChannelRead(msg);
			}
		}else{
			ctx.fireChannelRead(msg);
		}
	}
	
	private void loginFailProcess() {
		NettyClient.runEnable = false;
	}

	public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
		ctx.fireExceptionCaught(cause);
	}
}
